package com.ship.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ship.auth.entity.vo.RegisterVo;
import com.ship.auth.mapper.UserCreateMapper;
import com.ship.auth.service.UserCreateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserCreateServiceImpl extends ServiceImpl<UserCreateMapper, RegisterVo> implements UserCreateService {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final SecureRandom secureRandom = new SecureRandom();

    @Autowired
    private UserCreateMapper userCreateMapper;

    @Override
    public String addUser(RegisterVo registerVo) {
//        String bimRemotePwd = registerVo.getBimRemotePwd();
        String nameToCheck = registerVo.getUserName();
//        QueryWrapper<RegisterVo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", nameToCheck);
//        List<RegisterVo> users = super.list(queryWrapper);

        String registerVo1 = userCreateMapper.getByUserName(registerVo.getUserName());
        RegisterVo registerVo2 = new RegisterVo();

        if (registerVo1 != null) {
            return "";
        }
        //        if (registerVo.getPassword() == null || registerVo.getPassword().isEmpty()) {
//            registerVo1.setPassword(MD5.encrypt(nameToCheck+nameToCheck));
//        }else {
//            registerVo1.setPassword(MD5.encrypt(registerVo.getPassword()));
//        }
//        String uid = generateUniqueID();
//        registerVo1.setUid(uid);
//        registerVo1.setBimRemotePwd(bimRemotePwd);
//        registerVo1.setIsDisabled(0);
//        registerVo1.setBimRemoteUser(registerVo.getBimRemoteUser());

        registerVo2.setUserName(nameToCheck);
        registerVo2.setNickName(nameToCheck);
        registerVo2.setDeptId(100);
        super.save(registerVo2);
        String userId = userCreateMapper.getIdByUserName(registerVo.getUserName());

        return userId;

    }

    @Override
    public String getId(String bimUid) {
        QueryWrapper<RegisterVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", bimUid);
        List<RegisterVo> ids = super.list(queryWrapper);

        if (ids == null || ids.isEmpty()){
            return "";
        }
        return ids.get(0).getUserId();
    }

    public String generateUniqueID() {
        StringBuilder sb = new StringBuilder(16);
        for (int i = 0; i < 16; i++) {
            int randomIndex = secureRandom.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);
        }
        return sb.toString();
    }
}
